package tum0r.sql;

import tum0r.utils.StringExtension;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.TimeZone;

/**
 * 工程: SQLTool<br>
 * 包: tum0r.sql<br>
 * 创建者: tum0r<br>
 * 创建时间: 2020/10/3 11:11<br>
 * <br>
 */
public class MySQL extends SQL {
    public static final int VERSION_5 = 5;
    public static final int VERSION_8 = 8;

    private int version = VERSION_8;

    public MySQL() throws ClassNotFoundException {
        init(VERSION_8);
    }

    public MySQL(int version) throws ClassNotFoundException {
        init(version);
    }

    private void init(int version) throws ClassNotFoundException {
        if (version == VERSION_5) {
            init("com.mysql.jdbc.Driver");
            this.version = VERSION_5;
        } else {
            init("com.mysql.cj.jdbc.Driver");
        }
    }

    public boolean open(String host, int port, String databaseName, String userName, String password) throws SQLException {
        boolean result = false;
        if (StringExtension.isNotNullOrOnlyWhiteSpace(host) && port >= 0 && port <= 65535 && StringExtension.isNotNullOrOnlyWhiteSpace(userName) && StringExtension.isNotNullOrEmpty(password)) {
            StringBuilder url = new StringBuilder();
            url.append("jdbc:mysql://");
            url.append(host);
            url.append(":");
            url.append(port);
            url.append("/");
            url.append(databaseName);
            url.append("?useUnicode=true&characterEncoding=utf8&useSSL=false");
            if (this.version == VERSION_8) {
                url.append("&serverTimezone=").append(TimeZone.getDefault().getID());
            }
            connection = DriverManager.getConnection(url.toString(), userName, password);
            if (connection != null) {
                connection.setAutoCommit(true);
                result = true;
            }
        }
        return result;
    }

    @Override
    public boolean open(String username, String password) throws SQLException {
        return open("", username, password);
    }

    @Override
    public boolean open(String databaseName, String username, String password) throws SQLException {
        return open(3306, databaseName, username, password);
    }

    @Override
    public boolean open() throws SQLException {
        return open(3306);
    }
}
